<template>
    <div style="background: #F4F7FD;padding-bottom:15px;">
        <navTop></navTop>
        <titleTab :examtitle="examtitle" :classlistbox="classlistbox" @classIdDate="classIdDate"></titleTab>
        <div class="contentzw" :style="screenWidth > 1400 ? 'width:1400px;;' : 'width:1200px;min-width:1200px;'">
            <div class="contentzwLeft">
                <span>可拖动调整表格顺序</span>
                <ul>
                    <li v-for="item in tabName" :key="item">{{item}}</li>
                </ul>
            </div>
            <div class="contentzwRight">
                <!-- 作业概览 -->
                <div class="homeworkgl">
                    <h3>{{className}}作业概览</h3>
                    <div>本班<b>{{overviewData.totalCount}}</b>人， 扫描<b>{{ overviewData.submitCount }}</b>人， 缺少<b>{{ overviewData.totalCount - overviewData.submitCount }}</b>人 ，<span @click="notuploadstuentishow=true">缺少名单</span>；</div>
                    <div>
                        全体最高分<b>{{ formatNumber(overviewData.examHighestScore) }}分</b>， 
                        全体平均分<b>{{ formatNumber(overviewData.examAvgScore) }}分</b>， 
                        优秀率<b>{{ formatNumber(overviewData.examExcellentPercent) }}%</b> / 
                        及格率<b>{{ formatNumber(overviewData.examPassPercent) }}%</b> / 
                        中位数为<b>{{ formatNumber(overviewData.examMedianScore) }}分</b> / 
                        标准差为<b>{{ formatNumber(overviewData.examStdDeviation) }}</b>；
                    </div>
                    <div>
                        {{className}}最高分<b>{{ formatNumber(overviewData.highestScore) }}分</b>， 
                        {{className}}平均分<b>{{ formatNumber(overviewData.avgScore) }}分</b>， 
                        优秀率<b>{{ formatNumber(overviewData.excellentPercent) }}%</b> / 
                        及格率<b>{{ formatNumber(overviewData.passPercent) }}%</b> / 
                        中位数为<b>{{ formatNumber(overviewData.medianScore) }}分</b> / 
                        标准差为<b>{{ formatNumber(overviewData.stdDeviation) }}</b>；</div>
                </div>
                <!-- 作答分布 -->
                <div class="answerBox">
                    <div class="subobjquestion">
                        <div class="subobjquestionTitle">
                            作答分布
                        </div>
                        <div class="rightlset">
                            <div>
                                <el-radio-group v-model="subObjquestion" size="mini">
                                    <el-radio-button label="1">客观题</el-radio-button>
                                    <el-radio-button label="2">主观题</el-radio-button>
                                </el-radio-group>
                            </div>
                            <span class="exportExcel" @click="objectiveQuestionDerivation">导出表格</span>
                        </div>
                    </div>
                    <!-- 客观题 -->
                    <div v-if="subObjquestion==1">
                        <!-- <el-card v-loading="loadingObjectiveQuestions"> -->
                        <el-table :height="objectiveAnswerData.length > 11 ? '60vh': ''" :data="objectiveAnswerData" border stripe
                            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
                            tooltip-effect="dark" style="width: 100%">
                            <el-table-column prop="questionNum" label="试题" align="center" />
                            <el-table-column prop="answer" label="答案" align="center" />
                            <!-- <el-table-column prop="score" label="分值" align="center" /> -->
                            <el-table-column label="平均分/满分" align="center">
                                <template slot-scope="scope">
                                    {{scope.row.avgScore}} / {{scope.row.score}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="scoreRate" label="班正答率(%)" align="center" />
                            <el-table-column prop="examScoreRate" label="全体正答率(%)" align="center" />
                            <el-table-column prop="fullScoreRate" label="得分率(%)" align="center" />
                            <!-- <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" /> -->
                            <el-table-column label="作答分布(标红为正确作答)" align="center" width="400">
                                <template slot-scope="scope">
                                <ul class="studentanswer">
                                    <li v-for="(option, index) in scope.row.newstudentAnswer" :key="index"
                                    :class="{ 'hover': option.includes(scope.row.answer) }">{{ option }}</li>
                                </ul>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- </el-card> -->
                    </div>
                    <!-- 主观题 -->
                    <div v-if="subObjquestion==2">
                        <el-table :height="subjectiveAnswerData.length > 11 ? '60vh': ''" :data="subjectiveAnswerData" border stripe
                            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
                            tooltip-effect="dark" style="width: 100%">
                            <el-table-column prop="questionNum" label="试题" align="center" />
                            <!-- <el-table-column prop="answer" label="答案" align="center" /> -->
                            <el-table-column label="平均分/满分" align="center">
                                <template slot-scope="scope">
                                    {{scope.row.avgScore}} / {{scope.row.score}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="scoreRate" label="班得分率(%)" align="center" />
                            <el-table-column prop="examScoreRate" label="全体得分率(%)" align="center" />
                            <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
                            <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
                            <el-table-column label="得分分布(标红为占比最多)" align="center" width="500">
                                <template slot-scope="scope">
                                <ul class="studentanswer">
                                    <li v-for="(option, index) in scope.row.newstudentAnswer" :key="index"
                                    :class="{ 'hover': isHighestPercentage1(scope.row, option) }">{{ option }}</li>
                                </ul>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
                <!-- 高频错题 -->
                <div>
                    <div class="subobjquestion">
                        <div class="subobjquestionTitle">
                            高频错题
                        </div>
                        <div class="rightlset">
                            <div class="screeningScope">
                                筛选范围：
                                <div>
                                    <el-input v-model="startRate" @change="startratechange" @input="stratrateinput"></el-input>
                                    <i>-</i>
                                    <el-input v-model="endRate" @change="endratechange" @input="endrateinput"></el-input>
                                </div>
                            </div>
                            <span @click="derivedExcel" class="exportExcel">导出表格</span>
                        </div>
                    </div>
                    <el-table :data="errorQuestions" border v-loading="loadingErrorQuestions"
                        :empty-text="errorQuestionsError || '暂无数据'" stripe
                        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }" class="custom-table"
                        tooltip-effect="dark" style="width: 100%"
                        :height="errorQuestions.length > 11 ? '70vh': ''">
                        <el-table-column prop="questionNum" label="试题" width="90" align="center" />
                        <el-table-column prop="questionTypeName" label="题型" width="90" align="center" />
                        <!-- <el-table-column label="知识点">
                            <template slot-scope="scope">
                                <Expandable :text="scope.row.knowledge"></Expandable>
                            </template>
                        </el-table-column> -->
                        <el-table-column prop="scoreRate" label="班得分率" width="140" align="center">
                        <template slot-scope="scope">
                            {{ formatNumber(scope.row.scoreRate) }}%
                        </template>
                        </el-table-column>
                        <el-table-column prop="examScoreRate" label="全体得分率" align="center">
                        <template slot-scope="scope">
                            {{ formatNumber(scope.row.examScoreRate) }}%
                        </template>
                        </el-table-column>
                        <el-table-column label="正确名单">
                        <template slot-scope="scope">
                            <span v-if="scope.row.correctlistname.length===0">-</span>
                            <Expandable v-else :text="scope.row.correctlistname"></Expandable>
                        </template>
                        </el-table-column>
                        <el-table-column prop="dimidiatelistname" label="半对名单">
                            <template slot-scope="scope">
                            <span v-if="scope.row.dimidiatelistname.length===0">-</span>
                            <Expandable v-else :text="scope.row.dimidiatelistname"></Expandable>
                        </template>
                        </el-table-column>
                        <el-table-column prop="errorlistname" label="错误名单">
                            <template slot-scope="scope">
                            <span v-if="scope.row.errorlistname.length===0">-</span>
                            <Expandable v-else :text="scope.row.errorlistname"></Expandable>
                        </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 两分五率 -->
                <div>
                    <div class="subobjquestion">
                        <div class="subobjquestionTitle">
                            两分五率
                        </div>
                        <div class="rightlset">
                            <div>
                                <el-radio-group v-model="twoFiverateradio" size="mini">
                                    <el-radio-button label="1">表格</el-radio-button>
                                    <el-radio-button label="2">图表</el-radio-button>
                                </el-radio-group>
                            </div>
                            <span class="exportExcel1">设置学业水平</span>
                        </div>
                    </div>
                    <div v-show="twoFiverateradio==1">
                        <el-table :data="scoreRateData" border stripe
                            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
                            tooltip-effect="dark" style="width: 100%">
                            <el-table-column label="全体/班级" align="center">
                            <template slot-scope="scope">
                                {{ scope.row.type == 0 ? '全体' : '班级' }}
                            </template>
                            </el-table-column>
                            <!-- <el-table-column prop="submitCount" label="提交人数" align="center" /> -->
                            <el-table-column prop="highestScore" label="最高分" align="center" />
                            <el-table-column prop="lowestScore" label="最低分" align="center" />
                            <el-table-column label="平均分" align="center"  prop="totalAvg">
                                <!-- <el-table-column prop="objectiveAvg" label="客观题" align="center" />
                                <el-table-column prop="subjectiveAvg" label="主观题" align="center" />
                                <el-table-column prop="totalAvg" label="全体" align="center" /> -->
                            </el-table-column>
                            <el-table-column label="标准差" align="center"  prop="totalStd">
                                <!-- <el-table-column prop="objectiveStd" label="客观题" align="center" />
                                <el-table-column prop="subjectiveStd" label="主观题" align="center" />
                                <el-table-column prop="totalStd" label="全体" align="center" /> -->
                            </el-table-column>
                            <el-table-column label="满分人数(占比)" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.fullScoreCount }}({{scope.row.fullScoreRate}})
                                </template>
                            <!-- <el-table-column prop="fullScoreCount" label="人数" align="center" />
                            <el-table-column prop="fullScoreRate" label="占比" align="center" /> -->
                            </el-table-column>
                            <el-table-column label="优秀人数(占比)" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.excellentCount }}({{scope.row.excellentRate}})
                                </template>
                            <!-- <el-table-column prop="excellentCount" label="人数" align="center" />
                            <el-table-column prop="excellentRate" label="占比" align="center" /> -->
                            </el-table-column>
                            <el-table-column label="良好人数(占比)" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.goodCount }}({{scope.row.goodRate}})
                                </template>
                            <!-- <el-table-column prop="goodCount" label="人数" align="center" />
                            <el-table-column prop="goodRate" label="占比" align="center" /> -->
                            </el-table-column>
                            <el-table-column label="及格人数(占比)" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.passCount }}({{scope.row.passRate}})
                                </template>
                            <!-- <el-table-column prop="passCount" label="人数" align="center" />
                            <el-table-column prop="passRate" label="占比" align="center" /> -->
                            </el-table-column>
                            <el-table-column label="低分人数(占比)" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.lowCount }}({{scope.row.lowRate}})
                                </template>
                            <!-- <el-table-column prop="lowCount" label="人数" align="center" />
                            <el-table-column prop="lowRate" label="占比" align="center" /> -->
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="width:100%;" v-show="twoFiverateradio==2">
                        <ul class="lengthTitle">
                            <li>满分占比</li>
                            <li>优秀占比</li>
                            <li>良好占比</li>
                            <li>及格占比</li>
                            <li>低分占比</li>
                        </ul>
                        <div ref="chartRef" style="width:1190px;height: 300px;"></div>
                    </div>
                </div>
                <!-- 多维细目表 -->
                <div>
                     <div class="subobjquestion">
                        <div class="subobjquestionTitle">
                            多维细目表
                        </div>
                    </div>
                    <div>
                        <el-table :data="matrixData" border stripe
                            :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
                            class="custom-table"
                            tooltip-effect="dark"
                            style="width: 100%">
                            <el-table-column prop="type" label="题型" align="center" width="120" />
                            <el-table-column prop="number" label="题号" align="center" width="130" />
                            <el-table-column prop="score" label="分值" align="center" width="80" />
                            <el-table-column label="知识点" align="center">
                                <template #default="scope">
                                    <span v-if="scope.row.knowledge === '待补充'" class="pending-data">
                                    {{ scope.row.knowledge }}
                                </span>
                                    <div class="expandable-cell" style="width:100%;" v-else>
                                        <Expandable :text="scope.row.knowledge"></Expandable>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="difficulty" label="难度" align="center" width="100">
                                <template #default="scope">
                                    <span class="tabbox" :class="getDifficultyClass(scope.row.difficulty)">{{scope.row.difficulty }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>
        <!-- 未上传名单  -->
        <div class="notuploadStudent" v-if="notuploadstuentishow">
            <div class="notuploadStudentContent">
                <h3>缺少名单</h3>
                <div id="content-to-copy" class="contentset">
                <!-- 优化后的分段显示 -->
                    <div class="student-groups">
                        <div v-for="(classInfo,studentIndex) in overviewData.unsubmittedList" :key="classInfo" class="student-row">
                            <!-- <span v-for="(student, studentIndex) in group" :key="studentIndex" class="student-name"> -->
                            {{ classInfo }}<span v-if="studentIndex < overviewData.unsubmittedList.length - 1">、</span>
                            <!-- </span> -->
                        </div>
                    </div>
                </div>
                <div class="elbuttonbox">
                <!-- <el-button @click="copyDivContentToClipboard('content-to-copy')">复制</el-button> -->
                <el-button type="primary" @click="notuploadstuentishow = false">关闭</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import navTop from "../../components/homework/headtop.vue"
import titleTab from "../../components/analysis/titleTab.vue"
import { mapGetters } from 'vuex';
import {getanalysis,get,postanalysis} from '../../request/api.js'
import * as XLSX from 'xlsx';
import Expandable from '@/components/analysis/expandable.vue';
import * as echarts from 'echarts'
export default {
    data(){
        return{
            examtitle:'',
            className:'高一1班',
            tabName:['作业概览','作答分布','高频错题','两分五率','多维细目表'],
            classlistbox:[],
            overviewData: {
                examHighestScore: 0,
                examAvgScore: 0,
                examExcellentPercent: 0,
                examPassPercent: 0,
                examMedianScore: 0,
                examStdDeviation: 0,
                fullScore: 0,
                highestScore: 0,
                avgScore: 0,
                excellentPercent: 0,
                passPercent: 0,
                medianScore: 0,
                stdDeviation: 0,
                totalCount: 0,
                submitCount: 0,
                unsubmittedList: []
            },
            subObjquestion:'1',
            objectiveAnswerData: [],
            subjectiveAnswerData: [],
            loadingObjectiveQuestions: false,
            loadingSubjectiveQuestions:false,
            loadingErrorQuestions:false,
            errorQuestions: [],
            errorQuestionRate: 40,
            errorQuestionsError: '',
            startRate:'0%',
            endRate:'40%',
            rate:'1',
            scoreRateData: [],
            examId:'',
            classId:'',
            matrixData:[],
            twoFiverateradio:"1",
            notuploadstuentishow:false,
            listDraglist:[],
            subjectObject:[]
        }
    },
    mounted(){
        this.examtitle = this.$route.query.title
        this.examId = this.$route.query.examId
        this.getclass(this.$route.query.examId)
        // this.initChart()
    },
    beforeDestroy(){
        this.chart && this.chart.dispose()
    },
    methods:{
        formatNumber (num) {
            if (num === undefined || num === null) return '--'
            return Number(num).toFixed(2)
        },
        //成绩概览
        performanceOverview(examId,classId){
            this.loadingObjectiveQuestions = true
            getanalysis(`api/score/overview/${examId}?classId=${classId}`).then(res => {
                console.info(res,'res')
                if(res.code==200){
                    this.overviewData = res.data
                    let obj={
                        mark:'作业概览',
                        overviewData:res.data
                    }
                    this.listDraglist.push(obj)
                    this.loadingObjectiveQuestions = false
                }else {
                    this.$message.error(res.message);
                }
            }).finally(() => {
                this.loadingObjectiveQuestions = false
            })
        },
        //作答分布  客观题
        objectiveQuestion(examId,classId){
            this.loadingObjectiveQuestions = true
            getanalysis(`api/score/objective-answer-distribution/${examId}?classId=${classId}`).then(res => {
                if(res.code==200){
                    this.objectiveAnswerData = res.data.map(item => ({
                        ...item,
                        newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
                    }));
                    this.subjectObject.push(this.objectiveAnswerData)
                }else {
                    this.$message.error(res.message);
                }
            }).finally(() => {
                this.loadingObjectiveQuestions = false
            })
        },
        //作答分布  主观题
        subjectiveQuestion(examId,classId){
            this.loadingSubjectiveQuestions = true
            getanalysis(`api/score/subjective-answer-distribution/${examId}?classId=${classId}`).then(res => {
                if(res.code==200){
                    this.subjectiveAnswerData = res.data.map(item => ({
                        ...item,
                        newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
                    }));
                    this.subjectObject.push(this.subjectiveAnswerData)
                    let obj={
                        mark:'作答分布',
                        overviewData:this.subjectObject
                    }
                    this.listDraglist.push(obj)
                }else {
                    this.$message.error(res.message);
                }
            }).finally(() => {
                this.loadingSubjectiveQuestions = false
            })
        },
        isHighestPercentage1 (row, option) {
            const options = row.newstudentAnswer;
            // 提取每个选项的百分比
            const percentages = options.map(opt => {
                const match = opt.match(/\((\d+\.\d+)%\)/);
                return match ? parseFloat(match[1]) : 0;
            });
            // 找出占比最高的选项
            const maxPercentage = Math.max(...percentages);
            // 判断当前选项是否是占比最高的且不是正确答案
            return percentages[options.indexOf(option)] === maxPercentage;
        },
        //导出客观题主观题表格
        objectiveQuestionDerivation(){
            if(this.subObjquestion==1){
                const data = [
                    ['试题', '答案', '分值','平均分','班正答率(%)','全体正答率(%)','满分率(%)','零分率(%)','学生作答'],
                ];
                this.objectiveAnswerData.map(item => {
                    let arr = []
                    arr.push(item.questionNum)
                    arr.push(item.answer)
                    arr.push(item.score)
                    arr.push(item.avgScore)
                    arr.push(item.scoreRate)
                    arr.push(item.examScoreRate)
                    arr.push(item.fullScoreRate)
                    arr.push(item.zeroScoreRate)
                    arr.push(item.newstudentAnswer.join(','))
                    data.push(arr)
                })
                const colWidths = data[0].map((_, colIndex) => {
                    return Math.max(
                    ...data.map(row => {
                        const cellValue = row[colIndex] || '';
                        return typeof cellValue === 'string' ? 
                        cellValue.toString().length * 1.8 : // 中文系数
                        10; // 默认宽度
                    }),
                    15 // 最小宽度
                    );
                });

                const ws = XLSX.utils.aoa_to_sheet(data);
                ws['!cols'] = colWidths.map(w => ({ wch: w })); // 设置列宽

                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, '客观题作答分布'); // 修正工作表名
                XLSX.writeFile(wb, '客观题作答分布.xlsx'); // 直接导出文件
            }else{
                const data = [
                    ['试题', '分值','平均分','班得分率(%)','全体得分率(%)','满分率(%)','零分率(%)','学生作答'],
                ];
                this.subjectiveAnswerData.map(item => {
                    let arr = []
                    arr.push(item.questionNum)
                    arr.push(item.score)
                    arr.push(item.avgScore)
                    arr.push(item.scoreRate)
                    arr.push(item.examScoreRate)
                    arr.push(item.fullScoreRate)
                    arr.push(item.zeroScoreRate)
                    arr.push(item.newstudentAnswer.join(','))
                    data.push(arr)
                })
                const colWidths = data[0].map((_, colIndex) => {
                    return Math.max(
                    ...data.map(row => {
                        const cellValue = row[colIndex] || '';
                        return typeof cellValue === 'string' ? 
                        cellValue.toString().length * 1.8 : // 中文系数
                        10; // 默认宽度
                    }),
                    15 // 最小宽度
                    );
                });
                const ws = XLSX.utils.aoa_to_sheet(data);
                ws['!cols'] = colWidths.map(w => ({ wch: w })); // 设置列宽
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, '主观题作答分布'); // 修正工作表名
                XLSX.writeFile(wb, '主观题作答分布.xlsx'); // 直接导出文件
            }
        },
        // 获取班级
        async getclass(id) {
            try {
                const { code, data, message } = await get('/work/class', { examId: id })
                if (code !== 200) {
                this.$message.error(message)
                return
                }

                this.classlistbox = data
                const { classId, gradeId } = data[0]
                this.classId = classId
                // 顺序执行
                await this.performanceOverview(id, classId)            // 成绩概览
                await this.objectiveQuestion(id, classId)              // 客观题
                await this.subjectiveQuestion(id, classId)             // 主观题
                await this.errorquestion(id, classId)                  // 高频错题
                await this.twoFiveRate(id, classId, gradeId, this.$route.query.subjectId)
                await this.multidimensionaldetailedlist(id, classId)   // 多维细目表
            } catch (e) {
                console.error(e)
                this.$message.error('数据加载失败')
            }
        },
        async classIdDate(data){
            let gradeId =  this.classlistbox.filter(item=>item.classId==data)[0].gradeId
            // alert(gradeId)
            await this.performanceOverview(this.examId,data)  //成绩概览
            await this.objectiveQuestion(this.examId,data) //客观题
            await this.subjectiveQuestion(this.examId,data) //主观题
            await this.errorquestion(this.examId,data) //高频错题
            await this.twoFiveRate(this.examId,data,gradeId,this.$route.query.subjectId)
            await this.multidimensionaldetailedlist(this.examId,data)//多维细目表
        },
        stratrateinput(val) {
            // 1. 去掉非法字符（只保留数字和 %）
            let value = val.replace(/[^0-9%]/g, '');
            // 2. 去掉多余的 %
            const percentCount = (value.match(/%/g) || []).length;
            if (percentCount > 1) {
                value = value.replace(/%/g, '') + '%';
            }
            // 3. 保证 % 在末尾
            if (value.includes('%') && !value.endsWith('%')) {
                value = value.replace(/%/g, '') + '%';
            }
            // 4. 限制数值范围 0-100
            let num = parseInt(value, 10);
            if (isNaN(num)) {
                value = '';                // 纯 %
            } else if (num > 100) {
                value = '100%';
            } else {
                value = num + (value.includes('%') ? '%' : '');
            }
            this.startRate = value;      // 直接同步到数据
            },

            // 结束得分率输入处理（同上）
            endrateinput(val) {
            let value = val.replace(/[^0-9%]/g, '');
            const percentCount = (value.match(/%/g) || []).length;
            if (percentCount > 1) {
                value = value.replace(/%/g, '') + '%';
            }
            if (value.includes('%') && !value.endsWith('%')) {
                value = value.replace(/%/g, '') + '%';
            }
            let num = parseInt(value, 10);
            if (isNaN(num)) {
                value = '';
            } else if (num > 100) {
                value = '100%';
            } else {
                value = num + (value.includes('%') ? '%' : '');
            }
            this.endRate = value;
        },
        async startratechange(val) {
            const newStartRate = Number(val.replace('%', ''));
            const endRate = Number(this.endRate.replace('%', ''));

            console.info('newStartRate', newStartRate);
            console.info('endRate', endRate);

            if (newStartRate > endRate) {
                this.$message.warning('开始得分率不能超出结束得分率');
                return false;
            }
            this.startRate = val;
            await this.errorquestion(this.examId,this.classId)
        },
        async endratechange(val) {
            const start = Number(this.startRate.replace('%', ''));
            const newEnd = Number(val.replace('%', ''));

            console.info('start', start);
            console.info('newEnd', newEnd);

            if (newEnd < start) {
                this.$message.warning('结束得分率不能小于开始得分率');
                return false;
            }
            this.endRate = val;
            await this.errorquestion(this.examId,this.classId)
        },
        //高频错题数据
       errorquestion(examId,classId){
            this.loadingErrorQuestions = true
            getanalysis(`api/score/error-questions/${examId}?classId=${classId}&startRate=${this.startRate.replace('%','')}&endRate=${this.endRate.replace('%','')}`).then(res => {
                if(res.code==200){
                    this.loadingErrorQuestions = false
                    res.data.forEach(item => {
                    // 初始化三个数组来存储不同类型的名单
                    item.errorlistname = [];
                    item.correctlistname = [];
                    item.dimidiatelistname = [];

                    // 遍历 rights 数组
                    item.answerRight.rights.forEach(right => {
                    const students = right.studentList.join(', '); // 将学生名字用逗号连接成一个字符串
                    switch (right.isRight) {
                        case "0": // 错误
                        item.errorlistname.push(students); // 将字符串添加到 errorlistname
                        break;
                        case "1": // 正确
                        item.correctlistname.push(students); // 将字符串添加到 correctlistname
                        break;
                        case "2": // 半对
                        item.dimidiatelistname.push(students); // 将字符串添加到 dimidiatelistname
                        break;
                        default:
                        break;
                    }
                    });

                    // 将数组中的字符串用逗号连接成一个完整的字符串
                    item.errorlistname = item.errorlistname.join(', ');
                    item.correctlistname = item.correctlistname.join(', ');
                    item.dimidiatelistname = item.dimidiatelistname.join(', ');
                });
                this.errorQuestions = res.data || []
                console.info('this.errorQuestions', this.errorQuestions)
                if (this.errorQuestions.length === 0) {
                    this.errorQuestionsError = `暂无得分率低于${this.errorQuestionRate}%的题目`
                }
                let obj={
                        mark:'高频错题',
                        overviewData:this.errorQuestions
                    }
                    this.listDraglist.push(obj)
                }else {
                    this.$message.error(res.message);
                }
            }).finally(() => {
                this.loadingErrorQuestions = false
            })
       },
        //高频错题
        derivedExcel() {
            const data = [
                ['题号', '题型', '知识点','班正答率/班得分率','全体正答率/全体得分率','全对学生','半对学生','错误学生'],
            ];
            this.errorQuestions.map(item => {
                let arr = []
                arr.push(item.questionNum)
                arr.push(item.questionTypeName)
                arr.push(item.knowledge)
                arr.push(this.formatNumber(item.scoreRate) + '%')
                arr.push(this.formatNumber(item.examScoreRate) + '%')
                arr.push(item.correctlistname)
                arr.push(item.dimidiatelistname)
                arr.push(item.errorlistname)
                data.push(arr)
            })
            // 动态计算每列最大宽度（按字符数）
            const colWidths = data[0].map((_, colIndex) => {
                return Math.max(
                ...data.map(row => {
                    const cellValue = row[colIndex] || '';
                    return typeof cellValue === 'string' ? 
                    cellValue.toString().length * 1.8 : // 中文系数
                    10; // 默认宽度
                }),
                15 // 最小宽度
                );
            });

            const ws = XLSX.utils.aoa_to_sheet(data);
            ws['!cols'] = colWidths.map(w => ({ wch: w })); // 设置列宽

            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, '高频错题'); // 修正工作表名
            XLSX.writeFile(wb, '高频错题.xlsx'); // 直接导出文件
        },
        // 两分五率
        twoFiveRate(examId,classId,gradeId,subjectId){
            let obj={
                classId,examId,gradeId,subjectId
            }
            postanalysis('api/score/score-rates',obj).then(res=>{
                if(res.code==200){
                     this.scoreRateData = res.data
                     const keys = ['fullScoreRate', 'excellentRate', 'goodRate', 'passRate', 'lowRate'];
                    // 一行转换
                    const series = keys.map(k => ({
                        name: { fullScoreRate:'满分占比', excellentRate:'优秀占比', goodRate:'良好占比', passRate:'及格占比', lowRate:'低分占比' }[k],
                        type: 'bar',
                        data: res.data.map(item => parseFloat(item[k]))   // 去掉 % 号并转成数字
                    }));
                    console.info('series',series)
                    this.initChart(series)
                    let obj={
                        mark:'两分五率',
                        overviewData:this.scoreRateData
                    }
                    this.listDraglist.push(obj)
                }else{
                    this.$message.error(res.message);
                }
            })
        },
        initChart(series) {
            this.chart = echarts.init(this.$refs.chartRef)
            const option = {
                color: ['#29CE67', '#A777FF', '#4985FF', '#FFAB77', '#FF7777'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' }
                },
                legend: {show: false},
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01],
                    max: 100,
                },
                yAxis: {
                    type: 'category',
                    data: ['全体占比', '班级占比']
                },
                series:series
            }
            this.chart.setOption(option)
        },
        // 多维细目表
        multidimensionaldetailedlist(examId,classId){
            getanalysis(`api/score/question-matrix/${examId}?classId=${classId}`).then(res => {
                console.info(res,'res')
                if(res.code==200){
                    this.matrixData = res.data;
                    let obj={
                        mark:'多维细目表',
                        overviewData:this.matrixData
                    }
                    this.listDraglist.push(obj)
                }else {
                    this.$message.error(res.message);
                }
            }).finally(() => {
               
            })
        },
        getDifficultyClass(difficulty) {
	        switch (difficulty) {
	          case '简单':
	            return 'green';
	          case '较易':
	            return 'zs';
	          case '一般':
	            return 'blue';
	          case '困难':
	            return 'yellow';
	          default:
	            return 'red';
	        }
	    },
    },
    computed: {
        ...mapGetters(['getScreenWidth']),
        screenWidth() {
        return this.getScreenWidth;
        },
    },
    components: { navTop,titleTab,Expandable }
}
</script>

<style scoped>
.contentzw{
    margin:10px auto 0;
    display: flex;
    justify-content: space-between;
}
.contentzwLeft{
    box-sizing: border-box;
    width:146px;
    background:#fff;
}
.contentzwLeft span{
    display: block;
    font-size:12px;
    color:#B3B8C2;
    text-align: center;
    padding:14px 0 14px;
    border-bottom:solid 1px #F5F6F8;
    margin:0 14px;
}
.contentzwLeft ul li{
    box-sizing: border-box;
    height:42px;
    padding:0 20px 0 34px;
    cursor: pointer;
    color: rgba(0, 0, 0, 0.6);
    line-height:42px;
    font-size:14px;
    background:url(../../assets/image/fenxi/drag.png) no-repeat 20px center;
    background-size:6px 14px;
}
.contentzwLeft ul li:hover,.contentzwLeft ul li.hover{
    color: #fff;
    background:#1A48DB url(../../assets/image/fenxi/drag1.png) no-repeat 20px center;
    background-size:6px 14px;
}
.contentzwRight{
    box-sizing: border-box;
    width:calc(100% - 161px);
    background:#fff;
    padding:20px;
}
.homeworkgl{
   font-size:14px; 
   padding:20px 24px;
   background:#FAFAFB url(../../assets/image/fenxi/bj.png) no-repeat right bottom;
   background-size:151px 85px;
   color:#5B6371;
   line-height: 24px;
    letter-spacing: 0.8px;
}
.homeworkgl h3{
    padding-bottom:10px;
    color:#2A303B;
    font-weight: 500;
}
.homeworkgl span{
    color:#1A48DB;
    text-decoration: underline;
    cursor: pointer;
}
.homeworkgl b{
   color:#1A48DB;
   font-weight: normal; 
}
.subobjquestion{
    display: flex;
    justify-content: space-between;
    padding-top:30px;
    margin-bottom:10px;
}
.subobjquestionTitle{
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 18px;
    color: #2A303B;
    background:url(../../assets/image/fenxi/title.png) no-repeat left center;
    background-size:12px 8px;
    padding-left:20px;
}
.subobjquestionTitle div{
    margin-left:40px;
}
.subobjquestionTitle b{
    font-size:12px;
    display: inline-block;
    margin-left:20px;
    color:#1A48DB;
    cursor: pointer;
}
.subobjquestion span{
    display: inline-block;
    width: 68px;
    height: 22px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: normal;
    line-height: 22px;
    text-align: center;
    cursor: pointer;
    background: #E8F3FF;
    color:#1A48DB;
}
>>> .el-card__body, .el-main{
    padding:0;
}
.studentanswer{
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	padding:4px 0;
}
.studentanswer li{
	background:rgb(242, 244, 251);
	border:solid 1px rgb(216, 225, 255);
	height: 30px;
	border-radius: 10px;
	font-size:14px;
	color:#1A48DB;
	padding:0 14px;
	line-height:30px;
	margin:4px 7px;
}
.studentanswer li.hover{
	background:rgb(250, 243, 245);
	border:solid 1px rgb(247, 212, 215);
	color:#EC555A;
}
.screeningScope{
    color:#5B6371;
    font-size:14px;
    display: flex;
    align-items: center;
}
.screeningScope div{
    display: flex;
    align-items: center;
    margin-left:8px;
}
.screeningScope div >>> .el-input{
    width:50px;
    height:22px;
    text-align: center;
    padding:0;
    margin:0;
}
.screeningScope div >>> .el-input__inner{
    padding:0;
    height:30px;
    text-align: center;
    border-radius: 0px;
    border:1px solid #DEE1E7;
    color:#1A48DB
}
.screeningScope div i{
    display: inline-block;
    padding:0 5px;
    font-style: normal;
}
.lengthTitle{
    display: flex;
    justify-content: right;
    position:relative;
    top:20px;
}
.lengthTitle li{
    font-size: 12px;
    color: #2c3542a6;
    letter-spacing: -0.22px;
    position: relative;
    padding-left:15px;
    margin-left:15px;
}
.lengthTitle li::before{
    content:'';
    width: 10px;
    height: 1px;
    position:absolute;
    left:0;
    top:50%;
    transform:translateY(-50%);
}
.lengthTitle li:nth-child(1)::before{
    background:#29CE67
}
.lengthTitle li:nth-child(2)::before{
    background:#A777FF
}
.lengthTitle li:nth-child(3)::before{
    background:#4985FF
}
.lengthTitle li:nth-child(4)::before{
    background:#FFAB77
}
.lengthTitle li:nth-child(5)::before{
    background:#FF7777
}
.tabbox{
	display: inline-block;
	width: 60px;
	height: 22px;
	border-radius: 10px;
}
.green {
  background: rgb(225, 248, 233);
  border: 1px solid #29CE67;
  color: #29CE67;
}
.zs {
  background: rgb(242, 236, 255);
  border: 1px solid rgb(224, 209, 255);
  color: #A777FF;
}
.blue {
  background: rgb(229, 238, 255);
  border: 1px solid rgb(167, 196, 254);
  color: #4985FF
}
.yellow {
  background: rgb(255, 243, 236);
  border: 1px solid rgb(255, 211, 181);
  color: #FFAB77;
}
.red {
  background: rgb(255, 236, 236);
  border: 1px solid rgb(255, 189, 189);
  color: #FF7777;
}
.rightlset{
    display: flex;
    align-items: center;
}
>>> .el-radio-button__orig-radio:checked+.el-radio-button__inner{
    background-color:#ffffff;
    border-color:#1A48DB;
    color:#1A48DB;
}
>>> .el-radio-button:first-child .el-radio-button__inner,>>> .el-radio-button:last-child .el-radio-button__inner{
    border-radius: 0;
}
>>> .el-radio-button--mini .el-radio-button__inner{
    padding:8px 15px;
    color:#B3B8C2;
}
.subobjquestion span.exportExcel{
    display: inline-block;
    width: 94px;
    height: 30px;
    background: #FFFFFF;
    border: 1px solid #DEE1E7;
    background:url(../../assets/image/fenxi/export.png) no-repeat 10px center;
    background-size:14px 14px;
    box-sizing: border-box;
    padding-left:20px;
    line-height:30px;
    color:#B3B8C2;
    border-radius:0;
    margin-left:24px;
}
.subobjquestion span.exportExcel:hover,.subobjquestion span.exportExcel.hover{
    color:#fff;
    background:#1A48DB url(../../assets/image/fenxi/export1.png) no-repeat 10px center;
    background-size:14px 14px;
}

.subobjquestion span.exportExcel1{
    display: inline-block;
    width: 122px;
    height: 30px;
    background: #FFFFFF;
    border: 1px solid #DEE1E7;
    background:url(../../assets/image/fenxi/edit.png) no-repeat 10px center;
    background-size:14px 14px;
    box-sizing: border-box;
    padding-left:20px;
    line-height:30px;
    color:#B3B8C2;
    border-radius:0;
    margin-left:24px;
}
.subobjquestion span.exportExcel1:hover,.subobjquestion span.exportExcel1.hover{
    color:#fff;
    background:#1A48DB url(../../assets/image/fenxi/edit1.png) no-repeat 10px center;
    background-size:14px 14px;
}
.notuploadStudent {
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100%;
  z-index: 100;
}

.notuploadStudentContent {
  width: 600px;
  max-height: 500px;
  background: #FFFFFF;
  box-shadow: 0 4px 16px 0 #5572921a;
  border-radius: 10px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 24px;
}

.notuploadStudentContent h3 {
  font-size: 18px;
  color: #2A303B;
}

.contentset {
  font-size: 16px;
  color: #5B6371;
  padding: 20px 0;
  max-height: 300px;
  overflow-y: auto;
}

/* 优化后的分段显示样式 */
.class-section {
  margin-bottom: 20px;
}

.class-title {
  font-weight: bold;
  color: #2A303B;
  margin-bottom: 8px;
  padding-bottom: 5px;
  border-bottom: 1px solid #E8F0FA;
}

.student-groups {
  padding-left: 10px;
  display: flex;
  flex-wrap: wrap;
}
.student-groups
.student-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 6px;
  line-height: 1.6;
}

.student-name {
  display: inline-block;
  margin-right: 5px;
}

.elbuttonbox {
  display: flex;
  align-items: center;
}

.elbuttonbox>>>.el-button {
  width: 124px;
  height: 34px;
  border-radius: 10px 10px 10px 10px;
  padding: 0;
  background:#1A48DB;
  border:solid 1px #1A48DB;
}
</style>
